/*
 * GaussSeidelSlover.cpp
 *
 *  Created on: 2015-1-3
 *      Author: cpp
 */

#include "GaussSeidelSlover.h"
#define tol 1.0e-10
Vec* GaussSeidelSlover::slove(Matrix& A,Vec& b){
     Vec* x = b.construct(A.getColL());
     Vec* x0;
     double norm = 0;
     while(true){
    	 x0 = x->clone();
    	 norm = 0;
    	 iter(*x,*x0,A,b,norm);
    	 delete x0;
    	 if(norm<tol){
    		 break;
    	 }
     }
     return x;
}

void GaussSeidelSlover::iter(Vec& x,Vec& x0,Matrix& A,Vec& b,double& norm){
    /**
     * xi(k+1)=(bi-sigma(aijxj(k+1) j=1..i-1)-sigma(aijxj(k))  j=i+1..n)/aii
     */
    for(int i=0;i<x.len();i++){
   	 double sum = 0;
   	 for(int j=0;j<i;j++){
   		sum+=A.get(i,j)*x.get(j);
   	 }
   	 for(int j=i+1;j<x0.len();j++){
   		 sum+=A.get(i,j)*x0.get(j);
   	 }
   	 x.set(i,(b.get(i)-sum)/A.get(i,i));
   	 norm+=pow(x.get(i)-x0.get(i),2);
    }
}
